package com.xie.smfs.handler;

import com.xie.smfs.Smfs;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.SimpleInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.screen.slot.Slot;
import net.minecraft.screen.slot.SlotActionType;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SecondInventoryScreenHandler extends ScreenHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger("SecondInventory");
    private final Inventory craftingInventory;

    // 客户端使用的构造函数
    public SecondInventoryScreenHandler(int syncId, PlayerInventory playerInventory) {
        this(syncId, playerInventory, new SimpleInventory(3));
        LOGGER.info("Client-side screen handler created");
    }

    // 服务端使用的构造函数
    public SecondInventoryScreenHandler(int syncId, PlayerInventory playerInventory, Inventory craftingInventory) {
        super(Smfs.SECOND_INVENTORY_SCREEN_HANDLER, syncId);
        LOGGER.info("Server-side screen handler created");
        this.craftingInventory = craftingInventory;

        // 检查服务器和客户端的物品栏大小是否匹配
        checkSize(craftingInventory, 3);

        // 添加玩家主物品栏 (3x9)
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 9; ++j) {
                this.addSlot(new Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
            }
        }

        // 添加玩家快捷栏 (1x9)
        for (int i = 0; i < 9; ++i) {
            this.addSlot(new Slot(playerInventory, i, 8 + i * 18, 142));
        }

        // 添加合成槽位
        this.addSlot(new Slot(craftingInventory, 0, 15, 20) {
            @Override
            public boolean canInsert(ItemStack stack) {
                return stack.getItem() == Items.GRASS_BLOCK;
            }
        });

        this.addSlot(new Slot(craftingInventory, 1, 15, 56) {
            @Override
            public boolean canInsert(ItemStack stack) {
                return stack.getItem().getMaxDamage() > 0;
            }
        });

        this.addSlot(new Slot(craftingInventory, 2, 139, 39) {
            @Override
            public boolean canInsert(ItemStack stack) {
                return false;
            }

            @Override
            public boolean canTakeItems(PlayerEntity playerEntity) {
                return !this.getStack().isEmpty();
            }

            @Override
            public void onTakeItem(PlayerEntity player, ItemStack stack) {
                ItemStack input1 = craftingInventory.getStack(0);
                ItemStack input2 = craftingInventory.getStack(1);

                if (!input1.isEmpty()) {
                    input1.decrement(1);
                    craftingInventory.setStack(0, input1.isEmpty() ? ItemStack.EMPTY : input1);
                }

                if (!input2.isEmpty() && input2.getItem().getMaxDamage() > 0) {
                    input2.damage(1, player, (p) -> p.sendToolBreakStatus(p.getActiveHand()));
                    if (input2.getDamage() >= input2.getMaxDamage()) {
                        craftingInventory.setStack(1, ItemStack.EMPTY);
                    } else {
                        craftingInventory.setStack(1, input2);
                    }
                }

                player.getWorld().playSound(null, player.getBlockPos(), SoundEvents.BLOCK_GRASS_BREAK,
                        SoundCategory.BLOCKS, 1.0F, 1.0F);

                updateResult();
            }
        });
    }

    // 从 PacketByteBuf 创建屏幕处理器的静态方法
    public static SecondInventoryScreenHandler createFromPacket(int syncId, PlayerInventory playerInventory, PacketByteBuf buf) {
        LOGGER.info("Creating screen handler from packet");
        return new SecondInventoryScreenHandler(syncId, playerInventory);
    }

    @Override
    public boolean canUse(PlayerEntity player) {
        return true;
    }

    @Override
    public void onSlotClick(int slotIndex, int button, SlotActionType actionType, PlayerEntity player) {
        super.onSlotClick(slotIndex, button, actionType, player);

        // 如果点击了输入槽，更新合成结果
        if (slotIndex >= 36 && slotIndex < 39) {
            updateResult();
        }
    }

    @Override
    public ItemStack quickMove(PlayerEntity player, int index) {
        ItemStack itemStack = ItemStack.EMPTY;
        Slot slot = this.slots.get(index);

        if (slot != null && slot.hasStack()) {
            ItemStack itemStack2 = slot.getStack();
            itemStack = itemStack2.copy();

            int playerInvStart = 0;
            int playerInvEnd = 36;
            int craftInvStart = 36;
            int craftInvEnd = 39;

            // 从合成槽移动到玩家物品栏
            if (index >= craftInvStart && index < craftInvEnd) {
                if (!this.insertItem(itemStack2, playerInvStart, playerInvEnd, false)) {
                    return ItemStack.EMPTY;
                }
            }
            // 从玩家物品栏移动到合成槽
            else {
                // 检查是否可以放入草方块槽
                if (itemStack2.getItem() == Items.GRASS_BLOCK) {
                    if (!this.insertItem(itemStack2, craftInvStart, craftInvStart + 1, false)) {
                        return ItemStack.EMPTY;
                    }
                }
                // 检查是否可以放入工具槽
                else if (itemStack2.getItem().getMaxDamage() > 0) {
                    if (!this.insertItem(itemStack2, craftInvStart + 1, craftInvStart + 2, false)) {
                        return ItemStack.EMPTY;
                    }
                }
                // 其他物品不能放入合成槽
                else {
                    return ItemStack.EMPTY;
                }
            }

            if (itemStack2.isEmpty()) {
                slot.setStack(ItemStack.EMPTY);
            } else {
                slot.markDirty();
            }

            updateResult();
        }

        return itemStack;
    }

    private void updateResult() {
        ItemStack input1 = craftingInventory.getStack(0);
        ItemStack input2 = craftingInventory.getStack(1);

        if (!input1.isEmpty() && input1.getItem() == Items.GRASS_BLOCK &&
                !input2.isEmpty() && input2.getItem().getMaxDamage() > 0) {
            // 合成泥土方块
            craftingInventory.setStack(2, new ItemStack(Items.DIRT));
        } else {
            craftingInventory.setStack(2, ItemStack.EMPTY);
        }

        this.sendContentUpdates();
    }

    @Override
    public void onContentChanged(Inventory inventory) {
        super.onContentChanged(inventory);
        if (inventory == craftingInventory) {
            updateResult();
        }
    }

    @Override
    public void onClosed(PlayerEntity player) {
        super.onClosed(player);
        // 关闭时将合成槽位的物品移回玩家库存
        for (int i = 0; i < 3; i++) {
            ItemStack stack = craftingInventory.getStack(i);
            if (!stack.isEmpty()) {
                player.getInventory().offerOrDrop(stack);
            }
        }
    }


}